<template>
  <div class="tts-player" v-show="audioUrl">
    <audio ref="audioPlayer" :src="audioUrl" @play="onPlay" @pause="onPause" @ended="onAudioEnded"></audio>
    <el-button 
      @click="togglePlay"
      size="small"
      circle
      type="primary"
    >
      <el-icon size="16">
        <VideoPlay v-if="!playing" />
        <Pause v-else />
      </el-icon>
    </el-button>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';

const props = defineProps({
  text: {
    type: String,
    required: true
  }
});

const audioPlayer = ref(null);
const audioUrl = ref('');
const playing = ref(false);

watch(() => props.text, async (newText) => {
  if (!newText) return;
  
  try {
    const response = await fetch('你的火山引擎API地址', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': '你的认证信息'
      },
      body: JSON.stringify({
        text: newText,
        voice_type: 'zh_female',
        sample_rate: 16000,
        speed_ratio: 1.2,
        need_replace: true  // 新增参数，表示需要替换当前播放的音频
      })
    });

    if (response.ok) {
      const blob = await response.blob();
      if (audioUrl.value) {
        URL.revokeObjectURL(audioUrl.value);
      }
      audioUrl.value = URL.createObjectURL(blob);
      
      // 确保DOM已更新后再播放
      await nextTick();
      if (audioPlayer.value) {
        try {
          const playPromise = audioPlayer.value.play();
          if (playPromise) {
            playPromise.catch(err => console.warn('自动播放失败:', err));
          }
        } catch (err) {
          console.warn('播放异常:', err);
        }
      }
    }
  } catch (error) {
    console.error('语音合成失败:', error);
  }
}, { immediate: false });

const togglePlay = () => {
  if (!audioPlayer.value) return;
  
  if (playing.value) {
    audioPlayer.value.pause();
  } else {
    audioPlayer.value.play();
  }
  playing.value = !playing.value;
};

const onAudioEnded = () => {
  playing.value = false;
};

// 新增音频事件处理函数
const onPlay = () => {
  playing.value = true;
};

const onPause = () => {
  playing.value = false;
};
</script>

<style scoped>
.tts-player {
  display: inline-flex;
  align-items: center;
  margin-left: 8px;
}

.el-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.el-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
